package core.process.pack;

import core.rb.PB;
import gui.processor.Processor;
import gui.utils.ProgBar;
import java.util.concurrent.CountDownLatch;
import java.util.HashMap;

/*Author: John Archer, Contact: john.archer.jpa@gmail.com*/
public class CodonPack extends Thread{
    private final CountDownLatch stopLatch;
    protected PB pIn;
    protected HashMap [] pOut;
    private Processor gp;
    private double mt;
    public CodonPack(Processor gp, CountDownLatch stopLatch, PB pack, double mt){
        super();
        this.gp = gp;
        this.pIn = pack;
        this.stopLatch = stopLatch;
        this.mt = mt;
        this.start();
    }
    public void run(){
        pOut = getCodons();
        stopLatch.countDown();
    }
    public HashMap <String, Integer> [] getPOut(){return pOut;}
    private HashMap <String, Integer>  [] getCodons(){
        HashMap <String, Integer> [] cData = new HashMap[pIn.getRef().getDNA().length()-3];
        for(int x=0; x<cData.length;x++){cData[x] = new HashMap <String, Integer>();}
        String codon="";
        int startCut, val;
        if(gp!=null){
            gp.dPrg(ProgBar.START, pIn.getSize());
            String dna;
            for(int z=0; z<pIn.getSize(); z++){
                if(this.mt==-1){dna = pIn.getScDNA(z);}
                else{dna = pIn.getScDNA(z, mt);}
                for(int s=pIn.getRead(z).getStart(); s<pIn.getRead(z).getEnd()-3 && s<pIn.getRef().getDNA().length()-3; s++){
                    startCut = s - pIn.getRead(z).getStart();
                    codon = dna.substring(startCut, startCut + 3);
                    if(cData[s].containsKey(codon)){
                        val = cData[s].get(codon).intValue();
                        cData[s].remove(codon);
                        cData[s].put(codon, ++val);
                    }
                    else{cData[s].put(codon, 1);}
                }
                gp.dPrg(ProgBar.UPDATE, z);
            }
            gp.dPrg(ProgBar.END, 0);
        }
        else{
            String dna;
            for(int z=0; z<pIn.getSize(); z++){
                if(this.mt==-1){dna = pIn.getScDNA(z);}
                else{dna = pIn.getScDNA(z, mt);}
                for(int s=pIn.getRead(z).getStart(); s<pIn.getRead(z).getEnd()-3 && s<pIn.getRef().getDNA().length()-3; s++){
                    startCut = s - pIn.getRead(z).getStart();
                    codon = dna.substring(startCut, startCut + 3);
                    if(cData[s].containsKey(codon)){
                        val = cData[s].get(codon).intValue();
                        cData[s].remove(codon);
                        cData[s].put(codon, ++val);
                    }
                    else{cData[s].put(codon, 1);}
                }
            }
        }
        return cData;
    }
}